#!/usr/bin/env bash
set -e
[ -n "$JENV_DEBUG" ] && set -x

resolve_link() {
  $(type -p greadlink readlink | head -1) "$1"
}

abs_dirname() {
  local cwd="$(pwd)"
  local path="$1"

  while [ -n "$path" ]; do
    cd "${path%/*}"
    local name="${path##*/}"
    path="$(resolve_link "$name" || true)"
  done

  pwd
  cd "$cwd"
}

resolvepath() {
  local cwd="$(pwd)" 
  cd $1
  echo "$(pwd)"
  cd "$cwd"
}

samedir()  {
  if [ -d $1 ] && [ -d $2 ]; then
  local path1="$(resolvepath $1)"
  local path2="$(resolvepath $2)"

  if [ $path1 == $path2 ]; then
   return 0; 
  else
   return 1;
  fi
fi
return 0;
}

if [ -z "${JENV_ROOT}" ]; then
  JENV_ROOT="${HOME}/.jenv"
else
  JENV_ROOT="${JENV_ROOT%/}"
fi
export JENV_ROOT



if [ -z "${JENV_DIR}" ]; then
  JENV_DIR="$(pwd)"
else
  cd "$JENV_DIR" 2>/dev/null || {
    echo "jenv: cannot change working directory to \`$JENV_DIR'"
    exit 1
  } >&2
  JENV_DIR="$(pwd)"
  cd "$OLDPWD"
fi
export JENV_DIR


shopt -s nullglob
                  


bin_path="$(abs_dirname "$0")"    
                  
if ! samedir "${JENV_ROOT}" "$bin_path/../"  ; then
   JENV_INSTALL_DIR=$(resolvepath "$bin_path/../")
else
    JENV_INSTALL_DIR=$JENV_ROOT
fi
   export JENV_INSTALL_DIR


for plugin_bin in "${JENV_ROOT}/plugins/"*/bin; do
  bin_path="${bin_path}:${plugin_bin}"
done  

export PATH="${bin_path}:${PATH}" 



hook_path="${JENV_HOOK_PATH}"
for plugin_hook in "${JENV_ROOT}/plugins/"*/etc/jenv.d; do      
  hook_path="${hook_path}:${plugin_hook}"
done   


export JENV_HOOK_PATH=$hook_path



shopt -u nullglob


command="$1"

case "$command" in
  "completions" | "init" | "doctor" )
    ;;
  *)
    if [[ "$JENV_LOADED" != "1" ]]
    then
      {
        echo "Warning‘: jenv has not been initialised in the current shell, run"
        echo '         eval "$(jenv init -)"'
        echo
      } >&2
    fi
    ;;
esac

case "$command" in
"" | "-h" | "--help" )
  echo -e "$(jenv---version)\n$(jenv-help)" >&2
  ;;
* )
  command_path="$(command -v "jenv-$command" || true)"   
  if [ -z "$command_path" ]; then
    echo "jenv: no such command \`$command'" >&2
    exit 1
  fi

  shift 1        
  exec "$command_path" "$@"
  ;;
esac
